//
//  MSLoginController.m
//  觅尚
//
//  Created by No.8 on 2019/3/19.
//  Copyright © 2019 No.8. All rights reserved.
//

#import "MSLoginController.h"
#import "MSLoginView.h"
#import "MSRegisterController.h"

#import "MSTaBbarController.h"

@interface MSLoginController ()

/** h界面view*/
@property(nonatomic,strong)MSLoginView *LoginView;

/** 验证码编号*/
@property(nonatomic,strong)NSString *msgId;

/** 数组*/
@property(nonatomic,strong)NSMutableArray *ListAarray;


/** 数组*/
@property(nonatomic,strong)NSMutableArray *MyAarray;

/** 数组*/
@property(nonatomic,strong)NSMutableDictionary *RoomAarray;


/** 数组*/
@property(nonatomic,strong)NSMutableDictionary *CaiwuDictionary;


@end

@implementation MSLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.ListAarray = [NSMutableArray new];
    self.MyAarray = [NSMutableArray new];
    [self AddLoginView];
    
    [self AnimationClick];
    
    
}

- (void)AddLoginView{
    
    self.LoginView = [[MSLoginView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:self.LoginView];
    
    
    
    self.LoginView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"登录bg"]];
    UIView * ImageView = [[UIView alloc] initWithFrame:self.LoginView.frame];
    UIImage * image = [UIImage imageNamed:@"登录bg"];
    ImageView.layer.contents = (__bridge id)image.CGImage;
    /** 设置对齐模式*/
    ImageView.layer.contentsGravity = kCAGravityResize;
    [self.LoginView addSubview:ImageView];
    
    [self.LoginView addSubview:self.LoginView.logintitle];
    
    [self.LoginView addSubview:self.LoginView.iphoneTextField];
    
    [self.LoginView addSubview:self.LoginView.codeButton];
    
    [self.LoginView addSubview:self.LoginView.iphonelineIMG];
    
    [self.LoginView addSubview:self.LoginView.codeTextField];
    
    [self.LoginView addSubview:self.LoginView.passworldlineIMG];
    
    [self.LoginView addSubview:self.LoginView.loginButton];
    
    [self.LoginView addSubview:self.LoginView.choseButton];
    
    [self.LoginView addSubview:self.LoginView.registerButton];
}
//添加事件
- (void)AnimationClick{
    //登录按钮
    [self.LoginView.loginButton addTarget:self action:@selector(AnimationloginClick) forControlEvents:UIControlEventTouchUpInside];
    
    //手机号登录按钮
    [self.LoginView.choseButton addTarget:self action:@selector(AnimationchoseButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    //获取验证码
    [self.LoginView.codeButton addTarget:self action:@selector(AnimationcodeButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    //注册按钮
    [self.LoginView.registerButton addTarget:self action:@selector(AnimationregisterButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    
}

/**
 * 点击登录按钮
 */
- (void)AnimationloginClick{
    [self.ListAarray removeAllObjects];
    [self.MyAarray removeAllObjects];
    [self.RoomAarray removeAllObjects];
    [self.CaiwuDictionary removeAllObjects];
    [MBManager showLoading];
    NSString *iphoneTextStr = [self.LoginView.iphoneTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *CodeTextStr = [self.LoginView.codeTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if (iphoneTextStr.length != 11) {
        [MBManager showBriefAlert:@"手机号不正确!"];
        [MBManager hideAlert];
        return;
    }
    if (CodeTextStr.length == 0) {
        [MBManager showBriefAlert:@"验证码不能为空!"];
        [MBManager hideAlert];
        return;
    }
    
    NSDictionary * params = @{@"phoneNumber":iphoneTextStr,@"msgId":self.msgId,@"code":CodeTextStr};
    [HTTPRequest POST:MSloginCode params:params succeed:^(id responseObject) {
        if (CodeStr) {
            [MBManager hideAlert];
            
            [MBManager showBriefAlert:@"登录成功"];
//            NSMutableArray * array = [NSMutableArray new];
//            for (NSDictionary * dict in responseObject[@"list"]) {
//                [array addObject:dict[@"bme_tag"]];
//                WYCLog(@"------%@",dict[@"bme_tag"]);
//            }
            WYCAccount * Account = [[WYCAccount alloc] initWithDic:responseObject[@"data"][@"user"]];
            
            [WYCAccountTool saveAccount:Account];
            
            [WYCIsAppLoginTool saveIsAppLogin:YES];
           
            [[NSUserDefaults standardUserDefaults] setObject:responseObject[@"list"] forKey:@"array"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            
            [[NSUserDefaults standardUserDefaults] setObject:responseObject[@"data"][@"businessName"] forKey:@"businessName"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            for (NSDictionary * dict in responseObject[@"list"]) {
                //                [self.ListAarray addObject:dict[@"bme_tag"]];
                
                if ([dict[@"bme_tag"] intValue] == 2) {
                    for (NSDictionary * mydict in dict[@"muBaseAbilityList"]) {
                        [self.MyAarray addObject:mydict];
                        [[NSUserDefaults standardUserDefaults] setObject:self.MyAarray forKey:@"MyAarray"];
                        //                        WYCLog(@"-----%@",self.MyAarray);
                        [[NSUserDefaults standardUserDefaults] synchronize];
                    }
                }
                self.RoomAarray = [NSMutableDictionary dictionaryWithCapacity:5];
                if ([dict[@"bme_tag"] intValue] == 6) {
                    for (NSDictionary * mydict in dict[@"muBaseAbilityList"]) {
                        [self.RoomAarray setObject:mydict forKey:mydict[@"key"]];
                        id objectValue = [self.RoomAarray objectForKey:@"room_open"];
                        WYCLog(@"objectValue-------%@",objectValue);
                        [[NSUserDefaults standardUserDefaults] setObject:self.RoomAarray forKey:@"RoomAarray"];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                    }
                }
                
                self.CaiwuDictionary = [NSMutableDictionary dictionaryWithCapacity:5];
                if ([dict[@"bme_tag"] intValue] == 5) {
                    for (NSDictionary * mydict in dict[@"muBaseAbilityList"]) {
                        [self.CaiwuDictionary setObject:mydict forKey:mydict[@"key"]];
                        id objectValue = [self.CaiwuDictionary objectForKey:@"room_open"];
                        WYCLog(@"objectValue-------%@",objectValue);
                        [[NSUserDefaults standardUserDefaults] setObject:self.CaiwuDictionary forKey:@"CaiwuDictionary"];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                    }
                }
                
            }
            
            MSTaBbarController *  MSTabBar = [[MSTaBbarController alloc] init];
            
            [self presentViewController:MSTabBar animated:NO completion:nil];
        }else{
            [MBManager hideAlert];
            [MBManager showBriefAlert:responseObject[@"msg"]];
            
        }
    } failure:^(NSError *error) {
        [MBManager hideAlert];
        [MBManager showBriefAlert:Failed];
    }];
}

/**
 * 手机号登录按钮
 */
- (void)AnimationchoseButtonClick{
    WYCLogFunc;
   
    
    [self dismissViewControllerAnimated:NO completion:nil];
    
}

/**
 * 获取验证码按钮
 */
- (void)AnimationcodeButtonClick{
    WYCLogFunc;
    NSString *iphoneTextStr = [self.LoginView.iphoneTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (iphoneTextStr.length != 11) {
        [MBManager showBriefAlert:@"手机号不正确!"];
        return;
    }else{
        
        [self timeCountDown];
        
        [self CodepostUrl];
    }
    
}
- (void)timeCountDown {
    __block int timeout = 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.LoginView.codeButton.userInteractionEnabled = YES;
                self.LoginView.codeButton.titleLabel.font = [UIFont systemFontOfSize:Fontfour];
                [self.LoginView.codeButton setTitle:@"重新接收" forState:UIControlStateNormal];
            });
        }else{
            int seconds = timeout % 90;
            NSString *strTime = [NSString stringWithFormat:@"%d秒后重发", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.LoginView.codeButton.userInteractionEnabled = NO;
                self.LoginView.codeButton.titleLabel.font = [UIFont systemFontOfSize:Fontfour];
                [self.LoginView.codeButton setTitle:strTime forState:UIControlStateNormal];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}


- (void)CodepostUrl{
    NSString *iphoneTextStr = [self.LoginView.iphoneTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSDictionary * params = @{@"phone":iphoneTextStr};
    [HTTPRequest POST:MSsendSms params:params succeed:^(id responseObject) {
        WYCLog(@"---------------%@",responseObject);
        if (CodeStr) {
            [MBManager showBriefAlert:@"发送成功"];
            self.msgId = responseObject[@"data"][@"msgId"];
        }else{
            
            [MBManager showBriefAlert:responseObject[@"msg"]];
        }
        
    } failure:^(NSError *error) {
        [MBManager showBriefAlert:Failed];
    }];
    
}
/**
 * 注册按钮
 */
- (void)AnimationregisterButtonClick{
    WYCLogFunc;
    MSRegisterController * RegisterVC = [[MSRegisterController alloc] init];
    [self presentViewController:RegisterVC animated:NO completion:nil];
    
}
@end
